<?php

namespace lib;

class RSA {

    /**
     * @var array
     */
    private $key;

    public function __construct() {
        $this->key = include "key.php";
    }

    // 服务端私钥
    public function getServerPrivateKey(): string {
        return $this->key["serverPrivateKey"];
    }

    // 客户端公钥
    public function getClientPublicKey(): string {
        return $this->key["clientPublicKey"];
    }

    // 公钥加密
    public function encrypt(string $data, string $publicKey = ""): string {
        openssl_public_encrypt($data, $encrypted, $publicKey ?: $this->getClientPublicKey());
        return base64_encode($encrypted);
    }

    // 私钥解密
    public function decrypt(string $data, string $privateKey = ""): string {
        openssl_private_decrypt(base64_decode($data), $decrypted, $privateKey ?: $this->getServerPrivateKey());
        return $decrypted;
    }

    // 私钥签名
    public function sign(string $data, string $privateKey = ""): string {
        openssl_sign($data, $signature, $privateKey);
        return base64_encode($signature);
    }

    // 公钥验签
    public function signVerify(string $data, string $sign, string $publicKey = ""): bool {
        return (bool)openssl_verify($data, base64_decode($sign), $publicKey ?: $this->getClientPublicKey());
    }


}